/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.nonmember;

import java.net.URLDecoder;
import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.ItemCart;
import model.ShoppingCart;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import service.ProductServiceLocal;

/**
 *
 * @author SONY
 */
public class AddCartStrutsAction extends org.apache.struts.action.Action {
    
    @EJB ProductServiceLocal productServiceLocal;

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //request.setCharacterEncoding("UTF-8");
        String errorMsg = "";
        String productID = "";
        try { 
            productID = request.getParameter("ProductID").trim();
            String productName = request.getParameter("ProductName");
            String imageName = request.getParameter("ImageName").trim();
            double unitPrice = Double.parseDouble(request.getParameter("UnitPrice"));
            String quantity = request.getParameter("quantity");
            String quantityExpr = "([0-9]+)";
            if (quantity.length() == 0) {
                errorMsg = "Giá trị nhập vào không hợp lệ!";
            } else if(!quantity.matches(quantityExpr)) {
               errorMsg = "Giá trị nhập vào không hợp lệ!";
            } else {
                int qty = Integer.parseInt(quantity);
                ServletContext context = servlet.getServletContext();
                productServiceLocal = (ProductServiceLocal) context.getAttribute("productServiceLocal");
                if(productServiceLocal.checkQOH_byPID(productID, qty)) {
                    //create ItemCart object
                    ItemCart item_cart = new ItemCart();
                    item_cart.setImageName(imageName);
                    item_cart.setProductID(productID);
                    item_cart.setProductName(productName);
                    item_cart.setUnitPrice(unitPrice);
                    item_cart.setQuantity(qty);
                    item_cart.setTotalLine(unitPrice * qty);
                    //get ShoppingCart object in the session-scope to add ItemCart object to shopping cart
                    HttpSession session = request.getSession();
                    ShoppingCart shopping_cart = (ShoppingCart) session.getAttribute("shopping_cart");
                    shopping_cart.addItemCart(item_cart);
                    if(request.getQueryString() == null) {
                        return mapping.findForward(SUCCESS);
                    } else if(request.getQueryString().equals("details")) {
                        return mapping.findForward("success_details");
                    } else if(request.getQueryString().equals("bycategory")) {
                        String categoryID = request.getParameter("CategoryID").trim();
                        request.setAttribute("cid", categoryID);
                        return mapping.findForward("success_bycategory");
                    } else {  
                        String keyword_pricechoice = request.getQueryString();
                        String[] str_array;
                        str_array = keyword_pricechoice.split("&");
                        String keyword = URLDecoder.decode(str_array[0], "UTF-8");
                        String price_choice = str_array[1];
                        request.setAttribute("keyword", keyword);
                        request.setAttribute("price_choice", price_choice);
                        return mapping.findForward("success_search");
                    }
                } else {
                    errorMsg = "Số lượng mua đã vượt mức số lượng hàng tồn kho!";
                }
            }
            
        } catch (Exception e) {
            System.err.println(e);
        }
        request.setAttribute("errorMsg", errorMsg);
        if(request.getQueryString() == null) {
            return mapping.findForward("error");
        } else if(request.getQueryString().equals("details")) {
            request.setAttribute("pid", productID);
            return mapping.findForward("error_details");
        } else if(request.getQueryString().equals("bycategory")) {
            String categoryID = request.getParameter("CategoryID").trim();
            request.setAttribute("cid", categoryID);
            return mapping.findForward("error_bycategory");
        } else {
            String keyword_pricechoice = request.getQueryString();
            String[] str_array;
            str_array = keyword_pricechoice.split("&");
            String keyword = URLDecoder.decode(str_array[0], "UTF-8");
            String price_choice = str_array[1];
            request.setAttribute("keyword", keyword);
            request.setAttribute("price_choice", price_choice);
            return mapping.findForward("error_search");
        }
    }
    
}
